package dq.study.concurrent.semaphore;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dongqun
 * @version 1.0
 * @description 多进程多处理情况下使用可重入锁
 * @date 2019/9/5 19:03
 */
public class SemaphoreService4 implements ISemaphoreService{

    private Semaphore semaphore = new Semaphore(2,true);//多处理场景下信号量其实没起作用

    private ReentrantLock lock = new ReentrantLock();

    public void doSomething(){
        try {
            semaphore.acquire();
            lock.lock();
            doSomethingMain();
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    private void doSomethingMain() throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+":doSomething--start:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        Thread.sleep(2000);
        System.out.println(Thread.currentThread().getName()+":doSomething--end:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

    }

}
